package com.xq.tmall.agu.timer;

import com.alibaba.excel.util.DateUtils;
import com.xq.tmall.entity.Stock;
import com.xq.tmall.entity.StockHistory;
import com.xq.tmall.service.StockHistoryService;
import com.xq.tmall.service.StockService;
import com.xq.tmall.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StockHistoryTimer {

    @Autowired
    private StockHistoryService stockHistoryService;

    @Autowired
    private StockService stockService;

    @Scheduled(cron = "0 15 10 * * ?")
    public void actualSchedule() {
        log.info("10点10开始执行第一次任务...");
        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
            boolean isWeek = DateUtil.isWeekend(dateTime);
            if(isWeek){
                log.info("周末不执行");
                return;
            }
            // 清理300天前的历史数据
            cleanOldHistoryData();

            // 获取所有股票信息
            List<Stock> stockList = stockService.findAllStockInfo();
            log.info("获取到 {} 只股票信息", stockList.size());

            // 批量插入历史记录
            if (!CollectionUtils.isEmpty(stockList)) {
                // 删除当天的数据
                SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd");
                Date now = new Date();
                stockHistoryService.nowDelete(sb.format(now));
                stockHistoryService.batchInsert(stockList);
                log.info("成功插入 {} 条历史股票数据", stockList.size());
            } else {
                log.warn("未获取到有效的股票信息");
            }
        } catch (Exception e) {
            log.error("历史股票数据更新失败", e);
        }
    }

    @Scheduled(cron = "0 30 14 * * ?")
    public void actual14Schedule() {
        log.info("14点30开始执行第一次任务...");
        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
            boolean isWeek = DateUtil.isWeekend(dateTime);
            if(isWeek){
                log.info("周末不执行");
                return;
            }
            // 清理300天前的历史数据
            cleanOldHistoryData();

            // 获取所有股票信息
            List<Stock> stockList = stockService.findAllStockInfo();
            log.info("获取到 {} 只股票信息", stockList.size());

            // 批量插入历史记录
            if (!CollectionUtils.isEmpty(stockList)) {
                // 删除当天的数据
                SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd");
                Date now = new Date();
                stockHistoryService.nowDelete(sb.format(now));
                stockHistoryService.batchInsert(stockList);
                log.info("成功插入 {} 条历史股票数据", stockList.size());
            } else {
                log.warn("未获取到有效的股票信息");
            }
        } catch (Exception e) {
            log.error("历史股票数据更新失败", e);
        }
    }

    /**
     * 每天17:10执行历史数据更新
     */
    @Scheduled(cron = "0 36 15 * * ?")
    public void dailyHistoryUpdate() {
        log.info("开始执行历史股票数据更新任务...");

        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
            boolean isWeek = DateUtil.isWeekend(dateTime);
            if(isWeek){
                log.info("周末不执行");
                return;
            }
            // 清理90天前的历史数据
            cleanOldHistoryData();

            // 获取所有股票信息
            List<Stock> stockList = stockService.findAllStockInfo();
            log.info("获取到 {} 只股票信息", stockList.size());

            // 批量插入历史记录
            if (!CollectionUtils.isEmpty(stockList)) {
                stockHistoryService.batchInsert(stockList);
                log.info("成功插入 {} 条历史股票数据", stockList.size());
            } else {
                log.warn("未获取到有效的股票信息");
            }
        } catch (Exception e) {
            log.error("历史股票数据更新失败", e);
        }
    }

    private void cleanOldHistoryData() {
        try {
            Date historyDate = DateUtil.addDay(new Date(), -300);
            String deleteDate = DateUtils.format(historyDate, "yyyy-MM-dd");
            stockHistoryService.historyDelete(deleteDate);
            log.info("已清理 {} 之前的历史数据", deleteDate);
        } catch (Exception e) {
            log.error("清理历史数据失败", e);
        }
    }

    private boolean isTodayDataExists() {
        Map<String, Object> params = new HashMap<>();
        params.put("historyDate", DateUtils.format(new Date(), "yyyy-MM-dd"));
        List<StockHistory> stockHistoryList = stockHistoryService.findStockHistoryList(params);
        return !CollectionUtils.isEmpty(stockHistoryList);
    }
}
